// pages/shoplist/shoplist.js
const util = require('../../utils/util.js')
const App = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isLogin: false,
    currentPage: 1,
    pageSize: 10,
    primaryCateList: [],
    secondCateList: [],
    threeCateList: [],
    selectPrimaryId: null,
    selectLeftId: null,
    selectRightId: null,
    goodsList: [],
    goodsId: null,
    loadmore: 'loading',
    scrollTop: 0,
    scrollGoodsTop: 0,
    navStyle: [],
    searchValue: '',
    empty_image: '',
    addShoppingCart: null, // 防抖中转
    scrollLeft: 0
  },

  //获取一级分类数据--类别
  async getPrimaryList() {
    try {
      util.request('/api/goods/cate', {}, 'GET').then(async (res) => {
        const result = res.data
        if (result.code !== 0) return
        const cateList = result.data
        let cate_id_act = null

        if (cateList.length <= 0) return
        // 默认展示第一个
        if (this.data.selectPrimaryId > 0) {
          cate_id_act = this.data.selectPrimaryId
        } else {
          cate_id_act = cateList[0].cate_id
        }

        this.getSecondList(cate_id_act)
        this.setData({
          primaryCateList: cateList,
          selectPrimaryId: cate_id_act
        })
      })
    } catch (err) {
      wx.showToast({
        title: err
      })
    }
  },
  //获取二级列表数据--类别
  getSecondList(cid) {
    try {
      util.request('/api/goods/cate?cid=' + cid, {}, 'GET').then((res) => {
        const result = res.data
        if (result.code !== 0) return
        const secondCateList = result.data

        if (secondCateList.length > 0) {
          // 默认展示第一个
          let second_cid = secondCateList[0].cate_id
          this.setData({
            secondCateList,
            selectLeftId: second_cid
          })

          this.getThreeList(second_cid)
        } else {
          this.setData({
            secondCateList: [],
            selectLeftId: null,
            threeCateList: [],
            selectRightId: null,
            goodsList: []
          })
        }
      })
    } catch (err) {
      wx.showToast({
        title: err
      })
    }
  },
  //获取三级分类列表--类别
  getThreeList(cid) {
    try {
      util.request('/api/goods/cate?cid=' + cid, {}, 'GET').then((res) => {
        const result = res.data
        if (result.code !== 0) return

        const threeCateList = result.data
        if (threeCateList.length > 0) {
          // 默认展示第一个
          let three_cid = threeCateList[0].cate_id
          this.setData({
            threeCateList: threeCateList,
            selectRightId: three_cid
          })

          this.getGoodsList(three_cid)
        } else {
          this.setData({
            threeCateList: [],
            selectRightId: null,
            goodsList: []
          })
        }
      })
    } catch (err) {
      wx.showToast({
        title: err
      })
    }
  },
  //获取商品列表数据
  async getGoodsList(cid, isSwitch = true) {
    this.setData({
      loadmore: 'loading'
    })

    // 初始化分页参数
    if (isSwitch) {
      this.data.currentPage = 1 // 当前页码，初始化为1
      this.onToTop()
    }
    // 初始化经纬度
    let lat = 0
    let lng = 0
    // const location = await wx.getLocation({
    //   type: 'wgs84', // 返回可以用于wx.openLocation的坐标
    // });
    // lat = location.latitude;
    // lng = location.longitude;

    //获取经纬度信息
    let position = wx.getStorageSync('position')
    if (position) {
      lat = position.lat
      lng = position.lng
    }

    try {
      const listParamsR = {
        lat,
        lng,
        cid,
        limit: this.data.pageSize,
        page: this.data.currentPage
      }

      const res = await util.request('/api/goods/index', listParamsR, 'GET')
      this.setData({ loadmore: 'end' })
      const result = res.data
      if (result.code != 0) return

      const goodsList = result.data

      if (isSwitch) {
        this.setData({ goodsList })
      } else {
        if (goodsList.length > 0) {
          this.setData({
            goodsList: this.data.goodsList.concat(goodsList)
          })
        }
      }
    } catch (err) {
      wx.showToast({
        title: err
      })
    }
  },
  //搜索--功能
  search: function (e) {
    if (!!this.data.searchValue) {
      wx.navigateTo({
        url: '/modules/goodsModule/pages/goodslist/goodslist?kw=' + this.data.searchValue
      })
    } else {
      wx.showToast({
        title: '请输入关键字！',
        icon: 'none'
      })
    }
  },

  /**
   * 顶部导航点击事件
   */
  bindlePrimaryCateTap(e) {
    this.scrollToCenter(e)
    let { id } = e.currentTarget
    id = id.substring(4)

    if (id == this.data.selectPrimaryId) return
    this.setData({
      selectPrimaryId: id
    })

    this.getSecondList(id)
  },

  /**
   * 二级分类导航点击事件
   */
  onSideBarChange(e) {
    const { value } = e.detail
    if (value == this.data.selectLeftId) return

    this.setData({ selectLeftId: value })
    this.getThreeList(value)
  },

  /**
   * 三级分类导航事件
   */
  bindleThreeCateTap(e) {
    const { activeKey } = e.detail
    if (activeKey == this.data.selectRightId) return

    this.setData({ selectRightId: activeKey })
    this.getGoodsList(activeKey)
  },

  /**
   * 顶部导航事件更新位置滑动
   */
  scrollToCenter: function (e) {
    let offsetLeft = 0
    // 获取点击元素的左偏移量
    typeof e == 'object' ? (offsetLeft = e.currentTarget.offsetLeft) : (offsetLeft = e)
    const pageWidth = this.data.navStyle.windowWidth // 获取页面宽度
    const elementWidth = 74 // 获取点击元素的宽度
    const scrollLeft = offsetLeft - (pageWidth - elementWidth) / 2 // 计算滚动位置，确保元素在中间
    this.setData({ scrollLeft }) // 更新滚动位置
  },

  /**
   * 商品点击事件
   */
  bindleRightItemTap(e) {
    const { index } = e.currentTarget.dataset

    this.setData({
      goodsId: index
    })

    wx.navigateTo({
      url: '/modules/goodsModule/pages/goodsinfo/goodsinfo?id=' + index
    })
  },

  /* 保存选择的规格 */
  async addcart(e) {
    this.data.addShoppingCart(e)
  },
  // 添加到购物车
  async addShopping() {
    let eventData = arguments[0]
    let _this = this
    let productInfo = eventData.currentTarget.dataset.item,
      list_id = ''
    if (util.isLogin() !== true) {
      return false
    }
    let token = wx.getStorageSync('token')
    await util
      .request(
        '/api/goods/details',
        {
          token: token,
          id: productInfo.id
        },
        'GET'
      )
      .then((response) => {
        list_id = response.data.data.list[0].id
      })
    //请求头参数
    const header = {
      Authorization: token
    }
    var params = {
      token: token,
      goods_id: productInfo.id,
      list_id: list_id,
      goods_number: 1
    }
    if (params.goods_id == '' || params.goods_id == undefined) {
      wx.showToast({
        title: '请选择完整商品规格',
        icon: 'error',
        duration: 1000 //持续的时间
      })
    } else if (params.list_id == '' || params.list_id == undefined) {
      wx.showToast({
        title: '请选择商品规格',
        icon: 'error',
        duration: 1000 //持续的时间
      })
    } else {
      util.request('/api/cart/addcart', params, 'POST').then((res) => {
        const reslut = res.data
        if (reslut.code == 0) {
          const data = reslut.data
          const goods = {
            goods_id: data.goodsid,
            goods_number: data.total,
            id: data.id,
            select: 1
          }
          try {
            let cart = wx.getStorageSync('cart')
            if (!cart) {
              cart = []
              cart.push(goods)
            } else {
              const addGoods = cart.find((item) => item.goods_id == data.goodsid)
              if (!addGoods) {
                cart.unshift(goods)
              } else {
                addGoods.goods_number = data.total
              }
            }

            wx.setStorageSync('cart', cart)
            util.setCartCount(cart)
          } catch (e) {
            console.log(e)
          }

          //设置购物车下标
          return util.showtoast(
            {
              msg: res.data.msg,
              icon: 'none'
            },
            1000
          )
        }
        util.showtoast(
          {
            msg: res.data.msg,
            icon: 'error'
          },
          1000
        )
      })
    }
  },

  /**
   * 滚动到底事件
   */
  scrollToLower(e) {
    if (this.data.loadmore === 'loading') return
    // 更新页码，准备获取下一页数据
    this.data.currentPage += 1
    this.getGoodsList(this.data.selectRightId, false)
  },

  /**
   * 商品滚动事件
   */
  handleGoodsScroll(e) {
    const { scrollTop } = e.detail
    this.setData({ scrollTop })
  },

  /**
   * 回到顶部
   */
  onToTop(e) {
    this.setData({
      scrollGoodsTop: 0
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      navStyle: App.globalData,
      selectPrimaryId: App.globalData.cateid,
      empty_image: util.Background_base64('static/image/goods/wujieguo.png'), // 转化本地图片地址为base64格式
      addShoppingCart: util.debounce(this.addShopping, 1000)
    })

    this.getPrimaryList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    let query = wx.createSelectorQuery()
    query
      .select('#cate' + this.data.selectPrimaryId)
      .boundingClientRect((res) => {
        if (res) {
          let { index } = res.dataset
          const width = 78
          const offsetLeft = 10 + width * index
          this.scrollToCenter(offsetLeft)
        }
      })
      .exec()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const token = wx.getStorageSync('token')
    if (token) {
      const isLogin = true
      if (this.data.isLogin !== isLogin) {
        this.setData({ isLogin })
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  onShareTimeline: function (e) {
    return App.onShareTimeline()
  }
})
